import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { TaskInfo } from '../types/task'

export const useTaskStore = defineStore('task', () => {
  // 任务列表状态
  const taskList = ref<TaskInfo[]>([])
  
  // 添加任务
  const addTask = (task: TaskInfo) => {
    // 检查任务是否已存在
    const existingIndex = taskList.value.findIndex(
      t => t.serviceName === task.serviceName && t.serviceMethod === task.serviceMethod
    )
    
    if (existingIndex >= 0) {
      // 更新现有任务
      taskList.value[existingIndex] = { ...task, status: 'running' }
    } else {
      // 添加新任务
      taskList.value.push({ ...task, status: 'running' })
    }
  }
  
  // 停止任务
  const stopTask = (serviceName: string, serviceMethod: string) => {
    const taskIndex = taskList.value.findIndex(
      t => t.serviceName === serviceName && t.serviceMethod === serviceMethod
    )
    
    if (taskIndex >= 0) {
      taskList.value[taskIndex].status = 'stopped'
    }
  }
  
  // 移除任务
  const removeTask = (serviceName: string, serviceMethod: string) => {
    const taskIndex = taskList.value.findIndex(
      t => t.serviceName === serviceName && t.serviceMethod === serviceMethod
    )
    
    if (taskIndex >= 0) {
      taskList.value.splice(taskIndex, 1)
    }
  }
  
  // 清空任务列表
  const clearTasks = () => {
    taskList.value = []
  }
  
  // 获取运行中的任务数量
  const getRunningCount = () => {
    return taskList.value.filter(task => task.status === 'running').length
  }
  
  // 获取已停止的任务数量
  const getStoppedCount = () => {
    return taskList.value.filter(task => task.status === 'stopped').length
  }
  
  // 获取错误的任务数量
  const getErrorCount = () => {
    return taskList.value.filter(task => task.status === 'error').length
  }
  
  return {
    taskList,
    addTask,
    stopTask,
    removeTask,
    clearTasks,
    getRunningCount,
    getStoppedCount,
    getErrorCount
  }
}) 